<?php
/**
 * Created by PhpStorm.
 * User: adminchyistrator
 * Date: 2018/12/8
 * Time: 9:21
 */

namespace app\adminchy\controller;

use app\adminchy\model\UserModel;
use think\Controller;
use think\Db;
use think\facade\Session;

class Login extends Controller
{
    public function index(){
        #如果有session就跳到主页
        if (Session::has('user')){
            $this->redirect('/adminchy/Index/index');
        }
        #获取用户名和密码
        $user = input('post.');
        if (!$user){
            #返回登录页面
            return view('Login/login');
        }

        $user['user_pwd'] = md5($user['user_pwd']);
        $res = Db::name('snake_user')->where(['user_name'=>$user['user_name'],'password'=>$user['user_pwd']])->find();
        if ($res){
            //修改用户登录信息
            $data= [
                'login_times'=>$res['login_times']+1,
                'last_login_ip'=>$_SERVER["REMOTE_ADDR"],
                'last_login_time'=>time()
            ];
            $map = [
                'user_name'=>$user['user_name'],
                'password'=>$user['user_pwd']
            ];
            $user = new UserModel();
// save方法第二个参数为更新条件
            $res2 = $user->save($data,$map);
            if($res2){
                Session::set('user.id',$res['id']);
                return json(['status'=>0,'message'=>'登录成功']);
            }
        }else{
            return json(['status'=>1,'message'=>'用户名或者密码错误']);
        }
    }
    public function login_out(){
        Session::delete('user');
        //$this->redirect('adminchy/Login/index');
        return view('Login/login');
    }
}